<template>
  <div
    class="widget-view group_container"
    :class="{
      active: selectWidget.key == element.key,
    }"
    @click.stop="handleSelectWidget"
  >
    <div v-if="element.options.showLabel" class="group_container_title">
      组容器
    </div>
    <div class="group_container_body">
      <draggable
        v-model="element.list"
        :no-transition-on-drag="true"
        v-bind="{
          group: 'widgets',
          ghostClass: 'ghost',
          animation: 200,
          handle: '.drag-widget',
        }"
        @end="handleMoveEnd"
        @add="(e) => handleWidgetAdd(e, element)"
      >
        <transition-group name="fade" tag="div" class="widget-columns">
          <template v-for="(el, i) in element.list">
            <template v-if="el.type == 'group'">
              <widget-form-group
                v-if="el && el.key"
                :key="el.key"
                :element="el"
                :select.sync="selectWidget"
                :index="i"
                :data="element"
                :remote="remote"
              />
            </template>
            <template v-else-if="el.type == 'tabs'">
              <widget-form-tabs-item
                v-if="el && el.key"
                :select.sync="selectWidget"
                :element="el"
                :key="el.key"
                :index="i"
                :data="element"
                :remote="remote"
              />
            </template>
            <template v-else-if="el.type == 'flexContainer'">
              <widget-form-flex-container
                v-if="el && el.key"
                :select.sync="selectWidget"
                :element="el"
                :key="el.key"
                :index="i"
                :data="element"
                :remote="remote"
              />
            </template>
            <template v-else>
              <widget-form-item
                :key="el.key"
                v-if="el.key"
                :element="el"
                :select.sync="selectWidget"
                :index="i"
                :data="element"
              />
            </template>
          </template>
        </transition-group>
      </draggable>
    </div>
    <div
      v-if="selectWidget.key == element.key"
      class="widget-view-drag widget-tabs-drag"
    >
      <i class="iconfont icon-drag drag-widget" />
    </div>
    <div
      v-if="selectWidget.key == element.key"
      class="widget-view-action widget-tabs-action"
    >
      <i class="iconfont icon-trash" @click.stop="handleWidgetDelete(index)" />
    </div>
  </div>
</template>

<script>
import Draggable from 'vuedraggable'
import WidgetFormItem from './WidgetFormItem'
import WidgetFormTabsItem from './WidgetFormTabsItem.vue'
import WidgetFormFlexContainer from './WidgetFormFlexContainer.vue'

import {
  basicComponents,
  layoutComponents,
  advanceComponents,
} from '../configs/componentsConfig.js'

import { optionsFields } from '@/configs/fieldConfigLimit.js'

export default {
  name: 'WidgetFormGroup',
  components: {
    Draggable,
    WidgetFormItem,
    WidgetFormTabsItem,
    WidgetFormFlexContainer,
  },
  props: ['element', 'select', 'index', 'data', 'remote'],
  data() {
    return {
      key: '',
      selectWidget: this.select,
    }
  },
  methods: {
    handleWidgetDelete(index) {
      if (this.data.list.length - 1 === index) {
        if (index === 0) {
          this.selectWidget = {}
        } else {
          this.selectWidget = this.data.list[index - 1]
        }
      } else {
        this.selectWidget = this.data.list[index + 1]
      }

      this.$nextTick(() => {
        this.data.list.splice(index, 1)
      })
    },
    handleMoveStart() {
      console.log('------------------------------------')
    },
    handleMoveEnd() {},
    handleWidgetAdd(evt, element) {
      const newIndex = evt.newIndex
      const to = evt.to
      console.log(element)
      //为拖拽到容器的元素添加唯一 key
      const key =
        Date.parse(new Date()) + '_' + Math.ceil(Math.random() * 99999)
      const listItem = element.list[newIndex]
      let tmp = {
        ...listItem,
        options: {
          ...listItem.options,
          remoteFunc: 'func_' + key,
        },
        key,
        // 绑定键值
        model: listItem.type + '_' + key,
        rules: [],
      }

      // 含有options选型字段需要添加选项
      if (optionsFields.indexOf(listItem.type) > -1) {
        tmp = {
          ...tmp,
          options: {
            ...tmp.options,
            options: tmp.options.options.map((item) => ({
              ...item,
            })),
          },
        }
      }

      // 布局组件
      if (listItem.type === 'grid') {
        // todo:
      }

      // 表单模板
      if (listItem.type === 'form') {
        const preWidgets = JSON.parse(
          JSON.stringify(this.data.list.slice(0, newIndex))
        )
        const sufWidgets = JSON.parse(
          JSON.stringify(this.data.list.slice(newIndex + 1))
        )

        tmp.form.list.forEach((formItem) => {
          const widget = this.generateWidget(formItem)
          preWidgets.push(widget)
        })
        this.$set(element, 'list', [...preWidgets, ...sufWidgets])
      } else {
        this.$set(element.list, newIndex, tmp)
      }
      this.selectWidget = element.list[newIndex]
    },
    handleSelectWidget() {
      this.selectWidget = this.element
    },
    generateWidget(widget) {
      let tmp = JSON.parse(JSON.stringify(widget))
      const key =
        Date.parse(new Date()) + '_' + Math.ceil(Math.random() * 99999)
      tmp = {
        ...tmp,
        key,
        model: `${tmp.type}_${key}`,
      }
      if (widget.type === 'tabs') {
        const tabs = tmp.tabs.map((item) => {
          const list = item.list.map((subItem) => {
            return this.generateWidget(subItem)
          })
          return {
            ...item,
            list,
          }
        })
        tmp.tabs = tabs
      } else if (widget.type === 'grid' || widget.type === 'flexContainer') {
        const columns = tmp.columns.map((item) => {
          const list = item.list.map((subItem) => {
            return this.generateWidget(subItem)
          })
          return {
            ...item,
            list,
          }
        })
        tmp.columns = columns
      }
      return tmp
    },
  },
  watch: {
    'element.columns': {
      handler(val) {
        console.log('columns change ==================')
        console.log(val)
        console.log('columns change end ==================')
      },
      deep: true,
    },
    selectWidget: {
      handler(val, oldVal) {
        if (JSON.stringify(val) !== JSON.stringify(oldVal)) {
          this.$emit('update:select', val)
        }
      },
      deep: true,
    },
    select(val) {
      this.selectWidget = val
    },
  },
}
</script>

<style lang="scss" scoped>
.group_container {
  padding: 10px 2px;
  display: flex;
  flex-direction: column;
  &.active {
    outline-color: #e6a23c !important;
    border-color: #e6a23c !important;
  }
  .widget-view-drag,
  .widget-view-action {
    background: #e6a23c !important;
  }
  .group_container_title {
    font-size: 14px;
    line-height: 1.725;
  }
}
.group_container_body {
  border: 1px dashed #ccc;
  min-height: 60px;
  display: flex;
  flex-direction: column;
  & > div {
    flex: 1;
    position: relative;
    display: flex;
    flex-direction: column;
  }
}
.widget-columns {
  flex: 1;
}
</style>
